package com.tianpengtech.front.mobile.passport;

import com.jfinal.aop.Before;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;
import com.tianpengtech.admin.appsetting.AppSettingDao;
import com.tianpengtech.common.GlobalConfigConstant;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.model.appsetting.AppSetting;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.fairauth.FairAuth;
import com.tianpengtech.common.model.fairext.FairExt;
import com.tianpengtech.common.model.fairphoto.FairPhoto;
import com.tianpengtech.common.model.fairwithdraw.FairWithdraw;
import com.tianpengtech.common.model.moneylog.MoneyLog;
import com.tianpengtech.common.model.task.Task;
import com.tianpengtech.common.model.task.TaskWh;
import com.tianpengtech.common.model.user.User;
import com.tianpengtech.common.validator.Validator;
import com.tianpengtech.common.validator.rules.numberic.MustBeNumberic;
import com.tianpengtech.common.validator.rules.string.StringLengthBetween;
import com.tianpengtech.common.validator.rules.string.StringMustBeRequired;
import com.tianpengtech.front.mobile.bankno.MobileBanknoService;
import com.tianpengtech.front.mobile.common.util.R;
import com.tianpengtech.front.mobile.common.util.TokenUtil;
import com.tianpengtech.front.mobile.common.util.U;
import com.tianpengtech.front.mobile.region.RegionService;
import com.tianpengtech.front.web.fair.FairService;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * Created by ggd on 2017/7/24 0024.
 */
public class MobilePassportService {
	public static MobilePassportService me = new MobilePassportService();
	private static FairExt fairExtDao = FairExt.dao;
	private static FairService fairService = new FairService();
	private static FairService fs = new FairService();
	private static FairAuth authDao = FairAuth.dao;
	private static final String TRAN_PWD_CACHE_KEY = "tranPwd_";
	private static MobileBanknoService mbs = MobileBanknoService.me;

	private static String domain = GlobalConfigConstant.DOMAIN;

	public R updateNickName(long id, String nickName) {
		R r = null;
		String regex = "^[a-z0-9A-Z\u4e00-\u9fa5]+$";  
        Matcher m = Pattern.compile(regex).matcher(nickName);
		if (!m.find()) {
			r = R.fail("用户昵称不能包含特殊符号");
		} else {
			Fair fair = new Fair();
			fair.set(Fair.ID, id);
			fair.set(Fair.NICK_NAME, nickName);
			fair.update();
			r = R.ok("操作成功");
		}
		return r;
	}

	public R updateDescript(long id, String descript) {
		R r = null;
		if (StringUtils.length(descript) > 50) {
			r = R.fail("个人信息说明不能超过50个字符");
		} else {
			Fair fair = new Fair();
			fair.set(Fair.ID, id);
			fair.set(Fair.DESCRIPT, descript);
			fair.update();
			r = R.ok("操作成功");
		}
		return r;
	}

	public R updateBgPhoto(long id, String bgPhoto,long photo_id) {
		R r = null;
		if (StringUtils.isEmpty(bgPhoto)) {
			r = R.fail("设置图片不能为空");
		} else {
			Fair fair = new Fair();
			fair.set(Fair.ID, id);
			fair.set(Fair.BG_PHOTO, bgPhoto);
			fair.update();
			
			
			String sql ="update "+FairPhoto.dao.tableName()+" set is_cover=0 where wh_id=?";
			Db.update(sql,id);
			
			new FairPhoto()
			.set(FairPhoto.ID, photo_id)
			.set(FairPhoto.IS_COVER, 1).update();
			;
			
			r = R.ok("操作成功");
		}
		
		return r;
	}

	public R updateBirthday(long id, String birthDay) {
		R r = null;
		if (StringUtils.isEmpty(birthDay)) {
			r = R.fail("生日信息不能为空");
		} else {
			Fair fair = new Fair();
			fair.set(Fair.ID, id);
			fair.set(Fair.BIRTHDAY, birthDay);
			fair.update();
			r = R.ok("操作成功");
		}
		return r;
	}

	public R updateGender(long id, String gender) {
		R r;
		if (StringUtils.isEmpty(gender)) {
			r = R.fail("性别不能为空");
		} else {
			Fair fair = new Fair();
			fair.set(Fair.ID, id);
			fair.set(Fair.GENDER, gender);
			fair.update();
			r = R.ok("操作成功");
		}
		return r;
	}

	public R updateAge(long id, int age) {
		R r;
		if (age <= 0 || age > 99) {
			r = R.fail("年龄范围只能是0-99之间");
		} else {
			Fair fair = new Fair();
			fair.set(Fair.ID, id);
			fair.set(Fair.AGE, age);
			fair.update();
			r = R.ok("操作成功");
		}
		return r;
	}

	public R updateArea(long id, String province, String city) {

		R r;
		if (StringUtils.isEmpty(province)) {
			r = R.fail("省份不能为空");
		} else if (StringUtils.isEmpty(city)) {
			r = R.fail("城市不能为空");
		} else {
			Fair fair = new Fair();
			fair.set(Fair.ID, id);
			fair.set(Fair.PROVINCE, province);
			fair.set(Fair.CITY, city);
			fair.update();
			r = R.ok("操作成功");
		}
		return r;
	}

	public R updateAvatar(long id, String photo) {

		R r;
		if (StringUtils.isEmpty(photo)) {
			r = R.fail("头像不能为空");
		} else {
			Fair fair = new Fair();
			fair.set(Fair.ID, id);
			fair.set(Fair.PHOTO, photo);
			fair.update();
			r = R.ok("操作成功");
			
			String sql ="update "+FairPhoto.dao.tableName()+" set is_header=0 where wh_id=?";
			Db.update(sql,id);
			
		}
		return r;
	}

	public R updateHonners(long wh_id, String honner, String honnerIndex,int platform_id) {
		R r;
		Set<String> ext_set = new HashSet<>();
		if (StringUtils.isEmpty(honner)) {
			r = R.fail("荣耀信息不能为空");
		} else {
			String[] honners = honner.split(",");
			for (String h : honners) {
				h = h.trim();
				Ret ret = isExtExist(h, FairExt.TYPE_HONNER);
				if (ret.isOk()) {
					ext_set.add(ret.getInt(FairExt.ID) + "");
					continue;
				}
				FairExt ext = new FairExt();
				ext.set(FairExt.ISSYSTEM, FairExt.ISSYSTEM_NO);
				ext.set(FairExt.NAME, honnerIndex);
				ext.set(FairExt.EXT, h);
				ext.set(FairExt.WH_ID, wh_id);
				ext.set(FairExt.PLATFORM_ID, platform_id);
				ext.set(FairExt.TYPE, FairExt.TYPE_HONNER);
				ext.save();
				ext_set.add(ext.getInt(FairExt.ID) + "");
			}
			if (ext_set.size() > 0) {
				Db.update("delete from fair_wh_ext_join where wh_id=? ", wh_id);
			}
			ext_set.forEach(ext -> {
				Record record = new Record();
				record.set("wh_id", wh_id);
				record.set("ext_id", ext);
				Db.save("fair_wh_ext_join", record);
			});
			CacheKit.remove(FairExt.CACHE_NAME, "static_" + FairExt.TYPE_HONNER + "_" + wh_id);
			r = R.ok("操作成功");
		}
		return r;
	}

	public R updateXqah(long wh_id, String xqah) {
		R r;
		List<FairExt> records = new ArrayList<FairExt>();
		if (StringUtils.isEmpty(xqah)) {
			r = R.fail("兴趣爱好信息不能为空");
		} else {
			String[] xqahs = xqah.split(",");
			for (String h : xqahs) {
				FairExt ext = new FairExt();
				ext.set(FairExt.ISSYSTEM, FairExt.ISSYSTEM_NO);
				ext.set(FairExt.NAME, h);
				ext.set(FairExt.TYPE, FairExt.TYPE_XQAH);
				ext.set(FairExt.WH_ID,wh_id);
				records.add(ext);
			}
			deleteExt(wh_id,FairExt.TYPE_XQAH);
			Db.batchSave(records, records.size());
			r = R.ok("操作成功");
		}
		return r;
	}

	public R updateScly(long wh_id, String scly) {
		R r;
		if (StringUtils.isEmpty(scly)) {
			r = R.fail("擅长领域不能为空");
		} else {
			new Fair().set(Fair.ID, wh_id).set(Fair.FANS_FEATURE, scly).update();
			String[] sclys = scly.split(",");
			List<FairExt> records = new ArrayList<FairExt>();
			for (String h : sclys) {
				FairExt ext = new FairExt();
				ext.set(FairExt.ISSYSTEM, FairExt.ISSYSTEM_NO);
				ext.set(FairExt.NAME, h);
				ext.set(FairExt.TYPE, FairExt.TYPE_SCLY);
				ext.set(FairExt.WH_ID, wh_id);
				records.add(ext);
			}
			deleteExt(wh_id,FairExt.TYPE_SCLY);
			Db.batchSave(records, records.size());
			r = R.ok("操作成功");
		}
		return r;
	}

	/**
	 * 保存网红信息
	 * 
	 * @param param
	 * @return
	 */
	public R saveOrUpdate(Map<String, String> param) throws Exception {
		try {
			// 获取荣誉信息
			String honner = param.get("honners");
			// 获取兴趣爱好
			String xqah = param.get("xqah");
			// 获取擅长领域
			String scly = param.get("scly");

			String photo = param.get("photo");
			String nickName = param.get("nick_name");
			String gender = param.get("gender");
			String age = param.get("age");
			String province = param.get("province");
			String city = param.get("city");
			Set<String> ext_set = new HashSet<>();
			// 保存荣誉信息
			if (StrKit.notBlank(honner)) {
				String[] honners = honner.split(",");
				for (String h : honners) {
					h = h.trim();
					Ret ret = isExtExist(h, FairExt.TYPE_HONNER);
					if (ret.isOk()) {
						ext_set.add(ret.getInt(FairExt.ID) + "");
						continue;
					}
					FairExt ext = new FairExt();
					ext.set(FairExt.ISSYSTEM, FairExt.ISSYSTEM_NO);
					ext.set(FairExt.NAME, h);
					ext.set(FairExt.TYPE, FairExt.TYPE_HONNER);
					ext.save();
					ext_set.add(ext.getInt(FairExt.ID) + "");
				}
			}
			// 保存兴趣爱好
			if (StrKit.notBlank(xqah)) {
				String[] xqahs = xqah.split(",");
				for (String h : xqahs) {
					h = h.trim();
					if (U.isInteger(h)) {
						ext_set.add(h);
						continue;
					}
					Ret ret = isExtExist(h, FairExt.TYPE_XQAH);
					if (ret.isOk()) {
						ext_set.add(ret.getInt(FairExt.ID) + "");
						continue;
					}
					FairExt ext = new FairExt();
					ext.set(FairExt.ISSYSTEM, FairExt.ISSYSTEM_NO);
					ext.set(FairExt.NAME, h);
					ext.set(FairExt.TYPE, FairExt.TYPE_XQAH);
					ext.save();
					ext_set.add(ext.getInt(FairExt.ID) + "");
				}
			}
			// 保存擅长领域
			if (StrKit.notBlank(scly)) {
				String[] sclys = scly.split(",");
				for (String h : sclys) {
					h = h.trim();
					if (U.isInteger(h)) {
						ext_set.add(h);
						continue;
					}
					Ret ret = isExtExist(h, FairExt.TYPE_SCLY);
					if (ret.isOk()) {
						ext_set.add(ret.getInt(FairExt.ID) + "");
						continue;
					}
					FairExt ext = new FairExt();
					ext.set(FairExt.ISSYSTEM, FairExt.ISSYSTEM_NO);
					ext.set(FairExt.NAME, h);
					ext.set(FairExt.TYPE, FairExt.TYPE_SCLY);
					ext.save();
					ext_set.add(ext.getInt(FairExt.ID) + "");
				}
			}

			Fair fair = new Fair();
			if (StrKit.notBlank(photo)) {
				fair.set(Fair.PHOTO, photo);
			}
			if (StrKit.notBlank(nickName)) {
				fair.set(Fair.NICK_NAME, nickName);
			}
			if (StrKit.notBlank(gender)) {
				fair.set(Fair.GENDER, gender);
			}
			if (StrKit.notBlank(age)) {
				fair.set(Fair.AGE, age);
			}
			if (StrKit.notBlank(province)) {
				fair.set(Fair.PROVINCE, province);
			}
			if (StrKit.notBlank(city)) {
				fair.set(Fair.CITY, city);
			}

			String id = param.get("id");
			if (StrKit.notBlank(id)) {
				fair.set(Fair.ID, id);
				fair.update();
			} else {
				fair.set(Fair.ID, param.get("uid"));
				fair.save();
				id = fair.getLong(Fair.ID) + "";
			}
			if (ext_set.size() > 0) {
				Db.update("delete from fair_wh_ext_join where wh_id=? ", id);
			}
			// 保存关联属性
			final String wh_id = id;
			ext_set.forEach(ext -> {
				Record record = new Record();
				record.set("wh_id", wh_id);
				record.set("ext_id", ext);
				Db.save("fair_wh_ext_join", record);
			});
			CacheKit.remove(FairExt.CACHE_NAME, "static_" + FairExt.TYPE_HONNER + "_" + wh_id);
			CacheKit.remove(FairExt.CACHE_NAME, "static_" + FairExt.TYPE_XQAH + "_" + wh_id);
			CacheKit.remove(FairExt.CACHE_NAME, "static_" + FairExt.TYPE_SCLY + "_" + wh_id);
			return R.ok("成功");
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

	}

	/**
	 * 获取详情
	 * 
	 * @param fairId
	 * @return
	 */
	public R getFairInfo(String fairId) {
		Fair fair = fairService.findById(Integer.parseInt(fairId));
		if (fair == null) {
			R r = R.ok("用户不存在");
			r.p("fair", "");
			return r;
		}
		
		
		String photo = fair.getStr(Fair.PHOTO);
		if(photo.equals("/upload/avatar/x.jpg")){
			photo = "http://www.ele-young.com/upload/avatar/x.jpg";
			fair.set(Fair.PHOTO, photo);
		}

		Record province = RegionService.me.findById(fair.getStr(Fair.PROVINCE));
		Record city = RegionService.me.findById(fair.getStr(Fair.CITY));

		String provinceStr = (province == null) ? "" : province.getStr("REGION_NAME");
		String cityStr = (city == null) ? "" : city.getStr("REGION_NAME");
		fair.put("provinceStr", provinceStr);
		fair.put("cityStr", cityStr);
		if(StringUtils.length(fair.getStr(Fair.DESCRIPT))>55){
			fair.put("descript", fair.getStr(Fair.DESCRIPT).substring(0,55)+"...");
		}
		fair.remove(Fair.DELETETAG);
		fair.remove(Fair.ID_CARD);
		String tran = fair.get(Fair.TRAN_PWD);
		fair.remove(Fair.TRAN_PWD);
		fair.put(Fair.TRAN_PWD, tran == null ? "0" : "1"); // 交易密码 0 未设置 1已设置
		fair.put("xqah", fair.getExt(FairExt.TYPE_XQAH,Integer.valueOf(fairId)));
		fair.put("scly", fair.getExt(FairExt.TYPE_SCLY,Integer.valueOf(fairId)));
		
		List<FairExt> list = fair.getExt(FairExt.TYPE_HONNER,Integer.valueOf(fairId));
		for (FairExt fairExt : list) {
			fairExt.set(FairExt.NAME,fairExt.getStr(FairExt.NAME));
			String honnerStr=fairExt.getStr(FairExt.EXT);
			if(StringUtils.length(honnerStr)>25){
				honnerStr = honnerStr.substring(0,25)+"...";
				fairExt.set(FairExt.EXT, honnerStr);
			}else{
				honnerStr = fairExt.getStr(FairExt.EXT);
			}
		}
		fair.put("honner",list);
		R r = R.ok("成功");
		r.p("fair", fair);
		return r;
	}

	/**
	 * 获取系统兴趣爱好
	 * 
	 * @return
	 */
	public R getXQAH(long wh_id) {
//		List<Record> list = new ArrayList<Record>();
//		String[] items = { "唱歌", "代购", "电影", "动漫", "画画", "旅游", "设计", "社交", "书评", "跳舞", "游戏", "运动" };
//		String[] icons = { "changge.png", "daigou.png", "dianying.png", "donghua.png", "huahua.png", "lvyou.png",
//				"sheji.png", "shejiao.png", "shuping.png", "tiaowu.png", "youxi.png", "yundong.png" };
//		String[] iconsselected = { "changge_selected.png", "daigou_selected.png", "dianying_selected.png",
//				"donghua_selected.png", "huahua_selected.png", "lvyou_selected.png", "sheji_selected.png",
//				"shejiao_selected.png", "shuping_selected.png", "tiaowu_selected.png", "youxi_selected.png",
//				"yundong_selected.png" };
		List<Record> list = getAppSettingByCategory(AppSetting.XINGQU);
		for (Record record : list) {
			record.set("name",record.getStr(AppSetting.NAME));
			record.set("id", record.getLong(AppSetting.ID));
			record.set("icon",record.getStr(AppSetting.UNSELECT_ICON));
			record.set("icon_selected",record.getStr(AppSetting.SELECT_ICON));
		}
		
		String sql="select * from "+FairExt.dao.tableName()+" where wh_id=? and type=?";
		List<FairExt> selectedList = FairExt.dao.find(sql,wh_id,FairExt.TYPE_XQAH);
		R r = R.ok("成功");
		r.p("list", list);
		r.p("selectedList", selectedList);
		return r;
	}

	public R getHonner() {
//		List<Record> list = new ArrayList<Record>();
//		String[] items = { "虎牙直播", "一直播", "斗鱼直播", "熊猫直播", "战旗直播", "龙珠直播", "哔哩哔哩", "花椒直播", "火猫直播", "映客直播", "咪咕直播", "kk直播" };
//		String[] icons = { "huya.png", "yi.png", "douyu.png", "xiongmao.png", "zhanqi.png", "longzhu.png",
//				"bilibili.png", "huajiao.png", "huomao.png", "yingke.png", "migu.png", "kk.png" };
//		String[] iconsSelected = { "huya_selected.png", "yi_selected.png", "douyu_selected.png", "xiongmao_selected.png", "zhanqi_selected.png", "longzhu_selected.png",
//				"bilibili_selected.png", "huajiao_selected.png", "huomao_selected.png", "yingke_selected.png", "migu_selected.png", "kk_selected.png" };
		List<Record> list = getAppSettingByCategory(AppSetting.HONOR);
		for (Record record : list) {
			record.set("name",record.getStr(AppSetting.NAME));
			record.set("id", record.getLong(AppSetting.ID));
			record.set("icon",record.getStr(AppSetting.UNSELECT_ICON));
			record.set("icon_selected",record.getStr(AppSetting.SELECT_ICON));
		}
		R r = R.ok("成功");
		r.p("list", list);
		return r;
	}

	/**
	 * 获取系统擅长领域
	 * 
	 * @return
	 */
	public R getSCLY(long wh_id) {
//		List<Record> list = new ArrayList<Record>();
//		String[] items = { "唱歌", "代购", "电影", "动漫", "画画", "旅游", "设计", "社交", "书评", "跳舞", "游戏", "运动" };
//		String[] icons = { "changge.png", "daigou.png", "dianying.png", "donghua.png", "huahua.png", "lvyou.png",
//				"sheji.png", "shejiao.png", "shuping.png", "tiaowu.png", "youxi.png", "yundong.png" };
//		String[] iconsselected = { "changge_selected.png", "daigou_selected.png", "dianying_selected.png",
//				"donghua_selected.png", "huahua_selected.png", "lvyou_selected.png", "sheji_selected.png",
//				"shejiao_selected.png", "shuping_selected.png", "tiaowu_selected.png", "youxi_selected.png",
//				"yundong_selected.png" };
		
		List<Record> list = getAppSettingByCategory(AppSetting.FANS);
		for (Record record : list) {
			record.set("name",record.getStr(AppSetting.NAME));
			record.set("id", record.getLong(AppSetting.ID));
			record.set("icon",record.getStr(AppSetting.UNSELECT_ICON));
			record.set("icon_selected",record.getStr(AppSetting.SELECT_ICON));
		}
		
		String sql="select * from "+FairExt.dao.tableName()+" where wh_id=? and type=?";
		List<FairExt> selectedList = FairExt.dao.find(sql,wh_id,FairExt.TYPE_SCLY);
		R r = R.ok("成功");
		r.p("list", list);
		r.p("selectedList", selectedList);
		return r;
	}

	/**
	 * 判断自定义属性是否存在
	 * 
	 * @param name
	 * @param type
	 * @return
	 */
	private Ret isExtExist(String name, int type) {
		String sql = String.format("select id from %s where %s=? and %s=? and %s=?", fairExtDao.tableName(),
				FairExt.TYPE, FairExt.ISSYSTEM, FairExt.NAME);
		FairExt ext = fairExtDao.findFirstByCache(FairExt.CACHE_NAME, "static_" + type + "_" + name, sql, type,
				FairExt.ISSYSTEM_NO, name);
		if (ext == null) {
			return Ret.fail();
		} else {
			Ret r = Ret.ok();
			r.put("id", ext.getInt(FairExt.ID));
			return r;
		}
	}

	/**
	 * 设置交易密码
	 * 
	 * @return
	 */
	public R setTranPwd(long uid, String old_pwd, String new_pwd) {
		Fair fair = fs.findById(Integer.parseInt(uid + ""));
		User user = User.dao.findById(uid);
		// 如果旧密码为空则是设置交易密码
		String tranPwd = fair.get(Fair.TRAN_PWD);
		if (StrKit.isBlank(tranPwd)) {
			String salt = user.get(User.SALT);
			String hashedPass = HashKit.sha256(salt + new_pwd);
			fair.set(Fair.TRAN_PWD, hashedPass);
			fair.update();
			CacheKit.remove(Fair.FAIR_CACHE_NAME, "fair_info_" + uid);
			return R.ok();
		} else {
			if (StrKit.isBlank(old_pwd)) {
				return R.fail("旧密码不能为空");
			} else {
				String salt = user.get(User.SALT);
				String hashedPass = HashKit.sha256(salt + old_pwd);
				if (tranPwd.toUpperCase().equals(hashedPass.toUpperCase())) {
					String hashedPass_new = HashKit.sha256(salt + new_pwd);
					fair.set(Fair.TRAN_PWD, hashedPass_new);
					fair.update();
					CacheKit.remove(Fair.FAIR_CACHE_NAME, "fair_info_" + uid);
					return R.ok();
				} else {
					return R.fail("旧密码不正确");
				}
			}
		}
	}

	/**
	 * 验证旧交易密码是否正确
	 * 
	 * @param uid
	 * @param old_pwd
	 * @return
	 */
	public R checkTranPwd(long uid, String old_pwd) {
		Fair fair = fs.findById(Integer.parseInt(uid + ""));
		User user = User.dao.findById(uid);
		String tranPwd = fair.get(Fair.TRAN_PWD);
		String salt = user.get(User.SALT);
		String hashedPass = HashKit.sha256(salt + old_pwd);
		if (tranPwd.toUpperCase().equals(hashedPass.toUpperCase())) {
			return R.ok("密码正确");
		} else {
			return R.fail("密码错误");
		}
	}

	/**
	 * 保存认证信息
	 * 
	 * @param param
	 * @return
	 * @throws ValidateException 
	 */
	public R saveAuth(Map<String, String> param) throws ValidateException {
		String username = param.get("user_name");
		String nickName = param.get("nick_name");
		String fans = param.get("fans");
		String screen = param.get("screenshot");
		String type = param.get("type");
		String uid = param.get("uid");
		
		
		Validator validator = new Validator();
		validator.addRule(new StringLengthBetween(nickName, "昵称长度只能是30字符以内", 1, 30));
		validator.addRule(new StringLengthBetween(username, "用户名只能是30字符以内", 1, 30));
		validator.addRule(new MustBeNumberic(fans, "粉丝数必须为数字，如1万，请输入10000"));
		validator.addRule(new StringMustBeRequired(screen, "请上传认证截图信息"));
		validator.excute();
		FairAuth fa = new FairAuth();
		fa.set(FairAuth.USER_NAME, username);
		fa.set(FairAuth.NICK_NAME, nickName);
		fa.set(FairAuth.FANS, fans);
		fa.set(FairAuth.SCREENSHOT, screen);
		fa.set(FairAuth.TYPE, type);
		fa.set(FairAuth.STATUS, FairAuth.STATUS_APPROVING);
		fa.set(FairAuth.WH_ID, uid);
		fa.save();
		return R.ok();
	}

	/**
	 * 获取认证信息列表
	 * 
	 * @param uid
	 * @return
	 */
	public R findAuth(long uid) {
		String sql = String.format("select * from %s where %s=? and %s=?", authDao.tableName(), FairAuth.DELETETAG,
				FairAuth.WH_ID);
		List<FairAuth> list = authDao.find(sql, 0, uid);
		Fair fair = Fair.dao.findById(uid);
		list.forEach(fa -> {
			String photo = fair.getStr(Fair.PHOTO);
			if(photo.equals("/upload/avatar/x.jpg")){
				photo = "http://www.ele-young.com/upload/avatar/x.jpg";
				fa.set(FairAuth.WH_ID,photo);
			}else{
				fa.set(FairAuth.WH_ID,photo);
			}
		});
		R r = R.ok();
		r.p("auths", list);
		return r;
	}

	
	public R unbindAuth(long id) {
		R r=null ;
		FairAuth fairAuth = FairAuth.dao.findById(id);
		int status = fairAuth.getInt(FairAuth.STATUS);
		if(status==FairAuth.STATUS_SUCCESS){
			r = R.fail("账号已认证成功，禁止当前操作");
		}else{
			FairAuth.dao.deleteById(id);
			r = R.ok("操作成功");
		}
		return r;
	}
	
	
	
	
	/**
	 * 获取点击数详情
	 * 
	 * @return
	 */
	public R getClickInfo(long id) {
		List<TaskWh> order = TaskWh.dao.find("SELECT wh_id, sum(click_num) FROM " + TaskWh.dao.tableName()
						+ " GROUP BY wh_id ORDER BY sum(click_num) desc");
		int no = 0;
		for (int i = 0; i < order.size(); i++) {
			TaskWh tw = order.get(i);
			if (tw.getInt(TaskWh.WH_ID).intValue() == id) {
				no = (i + 1);
				break;
			}
		}
		R r = R.ok();
		r.p("no", no);
		// 获取点击详情
		List<TaskWh> taskwhs = TaskWh.dao
				.find("select task.`status`,task.`task_start_time`,task.`task_end_time`,task.id,task.task_title,tw.click_num from "
						+ TaskWh.dao.tableName() + " tw LEFT JOIN " + Task.dao.tableName()
						+ " task  on tw.task_id=task.id where tw.deletetag=0 and tw.wh_id=? order by task.id desc", id);
		long sum = 0;
		for (TaskWh taskWh : taskwhs) {
			sum += (taskWh.getInt("click_num"));
		}
		r.p("list", taskwhs);
		r.p("sum", sum);
		return r;
	}

	/**
	 * 获取转化数详情
	 * 
	 * @return
	 */
	public R getCvsInfo(long id) {
		List<TaskWh> order = TaskWh.dao.findByCache(TaskWh.CACHE_NAME_NO, "cache_taskwh_click_no",
				"SELECT wh_id, sum(cvs_num) FROM " + TaskWh.dao.tableName()
						+ " GROUP BY wh_id ORDER BY sum(cvs_num) desc");
		int no = 0;
		for (int i = 0; i < order.size(); i++) {
			TaskWh tw = order.get(i);
			if (tw.getInt(TaskWh.WH_ID).intValue() == id) {
				no = (i + 1);
				break;
			}
		}
		R r = R.ok();
		r.p("no", no);
		// 获取转化详情
		List<TaskWh> taskwhs = TaskWh.dao
				.find("select task.`status`,task.`task_start_time`,task.`task_end_time`,task.id,task.task_title,tw.cvs_num from "
						+ TaskWh.dao.tableName() + " tw LEFT JOIN " + Task.dao.tableName()
						+ " task  on tw.task_id=task.id where tw.deletetag=0 and tw.wh_id=? order by task.id desc", id);
		long sum = 0;
		for (TaskWh taskWh : taskwhs) {
			sum += (taskWh.getInt("cvs_num"));
		}
		r.p("list", taskwhs);
		r.p("sum", sum);
		return r;
	}

	/**
	 * 个人中心
	 * 
	 * @param id
	 * @return
	 */
	public R center(long id) {
		Fair fair = Fair.dao.findFirst(
				"select * from " + Fair.dao.tableName() + " where " + Fair.DELETETAG + "=? and " + Fair.ID + "=?", 0,
				id);
		if (fair == null) {
			return R.fail("用户不存在");
		}
		R r = R.ok();
		r.p("status", fair.get(Fair.STATUS));
		r.p("click", fair.getClick());
		r.p("cvs", fair.getCvs());
		return r;
	}

	/**
	 * 我的钱包
	 * 
	 * @return
	 */
	public R getWallet(long id) {
		// 获取可用余额 昨日收益 总收益
		Fair fair = Fair.dao.findFirst(
				"select * from " + Fair.dao.tableName() + " where " + Fair.DELETETAG + "=? and " + Fair.ID + "=?", 0,
				id);
		if (fair == null) {
			return R.fail("用户不存在");
		}
		R r = R.ok();
		r.p("money", fair.get(Fair.MONEY));
		FairWithdraw log = FairWithdraw.dao.findFirst(
				"select SUM(money) as money from " + FairWithdraw.dao.tableName()
						+ " where DATE_FORMAT(create_time, '%Y%m%d')=DATE_FORMAT(?, '%Y%m%d') and wh_id=? and status=?",
				getYesterDay(), id,FairWithdraw.STATUS_SUCCESS);
		if (log == null) {
			r.p("yesterday", 0);
		} else {
			r.p("yesterday", log.get("money"));
		}
		MoneyLog sumlog = MoneyLog.dao
				.findFirst("select SUM(money) as money from " + MoneyLog.dao.tableName() + " where wh_id=? and deletetag=? and state=? ", 
						id,MoneyLog.STATUS_SUCCESS,MoneyLog.STATE_ADD);
//		String sql = "select SUM(money) as money from "+FairWithdraw.dao.tableName()+" where wh_id=? and status=?";
//		FairWithdraw sumlog= FairWithdraw.dao.findFirst(sql,id,FairWithdraw.STATUS_SUCCESS);
		if (sumlog == null) {
			r.p("all", 0);
		} else {
			r.p("all", sumlog.get("money"));
		}
		return r;
	}

	/**
	 * 获取昨天
	 * 
	 * @return
	 */
	private Date getYesterDay() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1);
		Date time = cal.getTime();
		return time;
	}

	public boolean isSetTransPwd(long uid) {
		Fair fair = fs.findById(Integer.parseInt(uid + ""));
		String tran_pwd = fair.getStr(Fair.TRAN_PWD);
		return (tran_pwd == null) ? false : true;
	}
	
	public boolean isOpenSMS(long uid) {
		Fair fair = fs.findById(Integer.parseInt(uid + ""));
		int sms_set = fair.getInt(Fair.SMS_SET);
		return (sms_set == 0) ? false : true;
	}

	/**
	 * 验证交易密码
	 * 
	 * @param tranPwd
	 * @param uid
	 * @return
	 */
	public R checkTranPwd(String tranPwd, long uid) {
		Fair fair = fs.findById(Integer.parseInt(uid + ""));
		User user = User.dao.findById(uid);
		String nowtranPwd = fair.get(Fair.TRAN_PWD); // 数据库中的交易密码
		String salt = user.get(User.SALT);
		String hashedPass = HashKit.sha256(salt + tranPwd); // 传入的交易密码加密
		if (nowtranPwd.toUpperCase().equals(hashedPass.toUpperCase())) {
			R r = R.ok("密码验证成功");
			String token = TokenUtil.getToken(); // 在提交提现请求时 需携带此token
			CacheKit.put(User.AUTH_CODE_CACHENAME, TRAN_PWD_CACHE_KEY + uid, token); // 缓存时间5分钟
			r.p("token", token);
			return r;
		} else {
			return R.fail("交易密码不正确");
		}
	}

	/**
	 * 提现请求
	 * 
	 * @return
	 */
	public R withdraw(String money, long uid, String token, String bankId) {
		if (!mbs.isBankNoExists(bankId)) {
			return R.fail("银行卡不存在");
		}
		Fair fair = fs.findById(Integer.parseInt(uid + ""));
		Double yue = fair.getDouble(Fair.MONEY); // 余额
		double tixian = Double.parseDouble(money); // 提现金额
		
		if (tixian <50) {
			return R.fail("提现金额必须超过￥50");
		}
		
		if (yue == null || tixian > yue.doubleValue()) {
			return R.fail("提现金额超出可用余额");
		}
		
		String cacheToken = CacheKit.get(User.AUTH_CODE_CACHENAME, TRAN_PWD_CACHE_KEY + uid);
		if (token.equals(cacheToken)) {
			CacheKit.remove(User.AUTH_CODE_CACHENAME, TRAN_PWD_CACHE_KEY + uid);
//			fair.set(Fair.MONEY, yue.doubleValue() - tixian);
			int version = fair.getInt(Fair.VERSION);
			//增加并发时候的乐观锁校验,以免产生重复的提交信息
			int netxtVersion = version+1;
			//String sql = "update "+Fair.dao.tableName()+" set "+Fair.MONEY+"=?,version=? where id=? and version=?";
			String sql = "update "+Fair.dao.tableName()+" set "+Fair.MONEY+"=?,"+Fair.AVALIABLE_FEE+"=?,version=? where id=? and version=?";
			
			double current =yue.doubleValue() - tixian;
			//减去当前的提现金额，更新当前数据网红数据的账户银行
			int result = Db.update(sql,current,yue.doubleValue(),netxtVersion,uid,version);
//			int result = Db.update(sql,yue,yue,netxtVersion,uid,version);
			if (result>0) {
				FairWithdraw fw = new FairWithdraw();
				fw.set(FairWithdraw.BANK_ID, bankId);
				fw.set(FairWithdraw.MONEY, tixian);
				fw.set(FairWithdraw.WH_ID, uid);
				if (fw.save()) {
					MoneyLog ml = new MoneyLog();
					ml.set(MoneyLog.WH_ID, uid);
					ml.set(MoneyLog.OPERID, fw.get(FairWithdraw.ID));
					ml.set(MoneyLog.STATE, MoneyLog.STATE_REDUCE);
					ml.set(MoneyLog.TYPE, MoneyLog.TYPE_TIXIAN);
					ml.set(MoneyLog.MONEY, tixian);
					ml.set(MoneyLog.DESCRIPTION, "用户提现，金额：" + tixian);
					ml.save();
					return R.ok();
				} else {
					return R.fail("提现失败");
				}
			} else {
				return R.fail("提现失败");
			}

		} else {
			return R.fail("token不正确");
		}

	}

	/**
	 * 删除照片
	 * 
	 * @param id
	 * @return
	 */
	public R delPhoto(long uid, String id) {
		String sql = String.format("select * from %s where %s=? and %s=? and %s=?", FairPhoto.dao.tableName(),
				FairPhoto.DELETETAG, FairPhoto.ID, FairPhoto.WH_ID);
		FairPhoto fp = FairPhoto.dao.findFirst(sql, 0, id, uid);
		if (fp == null) {
			return R.fail("照片不存在");
		} else {
			fp.set(FairPhoto.DELETETAG, 1);
			if (fp.update()) {
				return R.ok();
			} else {
				return R.fail("删除失败");
			}
		}
	}

	/**
	 * 保存网红图片
	 * 
	 * @return
	 */
	public R savePhoto(long uid, String picUrl) {
		FairPhoto fp = new FairPhoto();
		fp.set(FairPhoto.URL, picUrl);
		fp.set(FairPhoto.WH_ID, uid);
		if (fp.save()) {
			return R.ok();
		} else {
			return R.fail("保存失败");
		}
	}

	/**
	 * 获取网红所有照片
	 * 
	 * @param uid
	 * @return
	 */
	public R getPhoto(long uid) {
		String sql = String.format("select * from %s where %s=? and %s=? ",
				FairPhoto.dao.tableName(), FairPhoto.DELETETAG, FairPhoto.WH_ID);
		List<FairPhoto> list = FairPhoto.dao.find(sql, 0, uid);
		R r = R.ok("成功");
		r.p("photos", list);
		return r;
	}

	public R deleteHonner(int id) {
		boolean result = FairExt.dao.deleteById(id);
		return (result) ? R.ok("操作成功") : R.fail("操作失败");
	}

	public R queryHonnersOfMine(long uid) {
		R r = R.ok("成功");
		List<FairExt> list = Fair.dao.getExt(FairExt.TYPE_HONNER,uid);
		for (FairExt fairExt : list) {
			fairExt.set("name",fairExt.getStr(FairExt.NAME));
		}
 		r.p("honners",list);
		return r;
	}
	
	private void deleteExt(long wh_id,int type){
		String sql="delete from "+FairExt.dao.tableName()+" where "+FairExt.TYPE+"=? and "+FairExt.WH_ID+"=?";
		Db.update(sql,type,wh_id);
	}
	
	
	private List<Record> getAppSettingByCategory(int category){
		return AppSettingDao.dao.getAppSettingByCategory(category);
	}
	
	public R setPublicPhoto(int id){
		R r;
		FairPhoto photo = FairPhoto.dao.findById(id);
		if(photo!=null){
			photo.set(FairPhoto.IS_PHOTO, FairPhoto.IS_PHOTO_YES);
			photo.update();
			r = R.ok("设置成功");
		}else{
			r =  R.fail("当前照片记录不存在");
		}
		return r;
	}
	
	
	public R cancelPublicPhoto(int id){
		R r;
		FairPhoto photo = FairPhoto.dao.findById(id);
		if(photo!=null){
			photo.set(FairPhoto.IS_PHOTO, FairPhoto.IS_PHOTO_NO);
			photo.update();
			r = R.ok("操作成功");
		}else{
			r =  R.fail("当前照片记录不存在");
		}
		return r;
	}
}
